package com.cmcc.pp.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.cmcc.pp.entity.UserEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zrspring.libv2.util.security.SecurePreferences;

import java.util.ArrayList;
import java.util.List;

/**
 * Version: 1.0
 * Author: rui
 * CreateDate: 2017年12月11日
 * Encoding:UTF-8
 * Description:
 */
public class UserManager {

    public static final String USER_INFO = "ua";
    public static final String USER_SECURE_PREFERENCES_FILE_NAME = "uprefs";

    private SecurePreferences securePreferences;

    private UserManager() {
    }

    private static class SingletonHolder {
        private static final UserManager INSTANCE = new UserManager();
    }

    public static final UserManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public UserEntity getUserEntity(Activity mActivity) {
        UserEntity userEntity = App.getInstance().getUserEntity();
        if (userEntity == null) {
            startLogin(mActivity);
            return null;
        }
        return userEntity;
    }

    private void startLogin(Activity context) {

    }

    //=================================
    //  储存用户数据的地方，获取加密的用户偏好设置
    //=================================
    public SecurePreferences getSecurePreferences(Context context) {
        if (securePreferences == null) {
            securePreferences = new SecurePreferences(context, "", USER_SECURE_PREFERENCES_FILE_NAME);
            SecurePreferences.setLoggingEnabled(false);
        }
        return securePreferences;
    }









    //=================================
    // 保存用户信息到本地
    //=================================
    public void saveUserInfoToLocal(final Context context, final UserEntity userEntity) {
        new Thread(){
            @Override
            public void run() {
                String userJson = new Gson().toJson(userEntity);
                getSecurePreferences(context);
                SecurePreferences.Editor editor = securePreferences.edit();
                editor.putString(USER_INFO, userJson);
                editor.commit();
            }
        }.start();
    }

    public UserEntity getLocalUserInfo(Context context) {
        getSecurePreferences(context);
        String userJson = securePreferences.getString(USER_INFO,"");
        if (TextUtils.isEmpty(userJson)) {
            return new UserEntity();
        } else {
            return new Gson().fromJson(userJson, UserEntity.class);
        }
    }

    public void cleanLocalUserInfo(Context context){
        getSecurePreferences(context);
        SecurePreferences.Editor editor = securePreferences.edit();
        editor.remove(USER_INFO);
        editor.commit();
    }
}
